package com.hurui.xiaoming.activity.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.BaseActivity;
import com.hurui.xiaoming.activity.creditor.CreditorActivity;
import com.hurui.xiaoming.activity.finance.FinanceActivity;
import com.hurui.xiaoming.activity.forgetpass.ForgetPassActivity;
import com.hurui.xiaoming.activity.main.MainActivity;
import com.hurui.xiaoming.activity.manager.ClientManagerActivity;
import com.hurui.xiaoming.activity.me.MyContractActivity;
import com.hurui.xiaoming.activity.register.RegisterActivity;
import com.hurui.xiaoming.bean.Li_Login_Result;
import com.hurui.xiaoming.myconfig.PamaryKeys;
import com.hurui.xiaoming.utils.CodeUtils;
import com.hurui.xiaoming.utils.DefultData;
import com.hurui.xiaoming.utils.StatusBarUtil;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {

    EditText phone_et;
    EditText password_et;
    EditText yanzhen_et;
    private TextView goto_register_btn ;
    TextView forgetText;
    private Button goto_main_btn ;
    ImageView yanzhen_iv;
    Map map;
    private CodeUtils codeUtils;

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.silde_line_color), 0);
        context = getApplicationContext();
        map = new HashMap();
        initView();
        initAction();
    }

    @Override
    public void initView() {
        phone_et = (EditText) findViewById(R.id.phone_et);           //账号
        password_et = (EditText) findViewById(R.id.password_et);    //第一遍密码
        yanzhen_et = (EditText) findViewById(R.id.yanzhen_et);      //第二遍密码

        goto_main_btn = (Button) findViewById(R.id.goto_main_btn);   //立即登录
        goto_register_btn = (TextView) findViewById(R.id.goto_register_btn);   //前往注册

        forgetText = (TextView) findViewById(R.id.forgetText);          //忘记密码

        yanzhen_iv = (ImageView) findViewById(R.id.yanzhen_iv);

        codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        yanzhen_iv.setImageBitmap(bitmap);
    }

    @Override
    public void initAction() {
        yanzhen_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                codeUtils = CodeUtils.getInstance();
                Bitmap bitmap = codeUtils.createBitmap();
                yanzhen_iv.setImageBitmap(bitmap);
            }
        });

        //立即登录
        goto_main_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //为空检测
                if(checkData(phone_et) && checkData(password_et)){
                    map.put("ui_phone",phone_et.getText().toString().trim());
                    map.put("ui_pwd",password_et.getText().toString().trim());
                    //图片验证码
                    String code = codeUtils.getCode();
                    if (code.equalsIgnoreCase(yanzhen_et.getText().toString().trim())) {
                        getIntentData(DefultData.getLogin,map);
                    } else {
                        onToast("验证码错误");
                    }
                }else{
                    onToast("密码或账号不能为空");
                }
            }
        });
        //前往注册
        goto_register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onOpenForResult(new Intent(mContext , RegisterActivity.class) , PamaryKeys.RequstSuccess);
            }
        });
        //忘记密码
        forgetText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //todo 忘记密码
                onOpen(new Intent(mContext , ForgetPassActivity.class));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == PamaryKeys.RequstSuccess){
            if(resultCode == PamaryKeys.ResultSuccess){
                onFinish();
            }
        }
    }

    //请求网络
    public void getIntentData(String url, Map<String , String> parmas){
        Call<Li_Login_Result> call = apiSevice.onHttpPostGetLogin(url,parmas);
        call.enqueue(new Callback<Li_Login_Result>() {
            @Override
            public void onResponse(Call<Li_Login_Result> call, Response<Li_Login_Result> response) {
                Li_Login_Result li_login_result = null;
                if(response.isSuccessful()){
                    li_login_result = response.body() ;

                    if("login_ok".equals(li_login_result.getStatus())){
                        //保存用户信息
                        saveUserInfo(li_login_result);
                        //普通用户
                        if("3".equals(li_login_result.getData().getUi_type()) ||
                                "7".equals(li_login_result.getData().getUi_type())){

                            onOpen(new Intent(mContext , MainActivity.class));
                            onFinish();
                        }else if("2".equals(li_login_result.getData().getUi_type())){      //财务用户

                            onOpen(new Intent(mContext , FinanceActivity.class));
                            onFinish();
                        }else if("5".equals(li_login_result.getData().getUi_type())){      //催款

                            onOpen(new Intent(mContext , CreditorActivity.class));
                            onFinish();
                        }else if ( "6".equals(li_login_result.getData().getUi_type()) ){     //客户经理

                            onOpen(new Intent(mContext , ClientManagerActivity.class));
                            onFinish();
                        }else if("9".equals(li_login_result.getData().getUi_type())){     //第三方人员
                            onOpen(new Intent(mContext , MyContractActivity.class));
                            onFinish();
                        }
                    }else if("Locked".equals(li_login_result.getStatus())){
                        onToast("账户被锁定");
                    }else if("nouser".equals(li_login_result.getStatus())){
                        onToast("账号或密码错误");
                    }
                }else{
                    onToast("登录失败");
                }
            }

            @Override
            public void onFailure(Call<Li_Login_Result> call, Throwable t) {
                onHttpFail( -1 , t.getMessage());
            }
        });
    }

    /**
     * 保存用户信息
     */
    public void saveUserInfo(Li_Login_Result li_login_result){
        //保存用户id
       WriteReadSharedPrefs.writeUserId(context, Integer.parseInt(li_login_result.getData().getUi_id()));
        // WriteReadSharedPrefs.writeUserId(context,32);
        //保存用户额度
        WriteReadSharedPrefs.writeUserLimitMoney(context, li_login_result.getData().getUi_limit());
        //保存用户上次登录时间
        WriteReadSharedPrefs.writeUserLastTime(context, Integer.parseInt(li_login_result.getData().getUi_lastlogintime()));
        //保存上次登录IP
        WriteReadSharedPrefs.writeUserLastIp(context, li_login_result.getData().getUi_lastloginip());

        //保存用户角色标示
        WriteReadSharedPrefs.writeUserUI_Type(context, li_login_result.getData().getUi_type());
    }
}
